import { defineStore } from 'pinia'
import type { baseWarehouse } from '@/types/base/BaseWarehouse'
import request from '@/utils/request'

// 仓库类型常量
export const WAREHOUSE_TYPES = {
  1: '原材料仓',
  2: '半成品仓',
  3: '成品仓',
  4: '不良品仓'
} as const

// 获取仓库类型标签
export const getWarehouseTypeLabel = (type: number): string => {
  return (WAREHOUSE_TYPES as Record<number, string>)[type] || '未知类型'
}

// 模拟数据
const mockWarehouses: baseWarehouse[] = [
  {
    warehouseId: 1,
    warehouseCode: 'WH-RAW-001',
    warehouseName: '原材料主仓库',
    warehouseType: 1,
    address: '工业园区A区1号',
    contactPerson: '张三',
    contactPhone: '13800138001',
    area: 2000.00,
    capacity: 5000.00,
    managerId: 1001,
    manager: '李经理',
    isActive: 1,
    createdAt: new Date('2023-01-15'),
    updatedAt: new Date('2023-01-15'),
    createdBy: 'admin',
    updatedBy: 'admin',
    isDeleted: 0
  },
  {
    warehouseId: 2,
    warehouseCode: 'WH-FIN-001',
    warehouseName: '成品仓',
    warehouseType: 3,
    address: '工业园区B区5号',
    contactPerson: '李四',
    contactPhone: '13900139001',
    area: 3000.00,
    capacity: 8000.00,
    managerId: 1002,
    manager: '王经理',
    isActive: 1,
    createdAt: new Date('2023-01-20'),
    updatedAt: new Date('2023-02-10'),
    createdBy: 'admin',
    updatedBy: 'admin',
    isDeleted: 0
  }
]

export const useBaseWarehouseStore = defineStore('baseWarehouse', {
  state: () => ({
    warehouses: [] as baseWarehouse[],
    loading: false,
    error: null as string | null,
    total: 0,
    currentPage: 1,
    pageSize: 10,
    searchParams: {
      warehouseCode: '',
      warehouseName: '',
      warehouseType: undefined as number | undefined,
      isActive: undefined as number | undefined
    }
  }),

  getters: {
    activeWarehouses: (state) => {
      return state.warehouses.filter(warehouse => warehouse.isActive === 1)
    },
    filteredWarehouses: (state) => {
      return state.warehouses
        .filter(warehouse => !state.searchParams.warehouseCode ||
          warehouse.warehouseCode.includes(state.searchParams.warehouseCode))
        .filter(warehouse => !state.searchParams.warehouseName ||
          warehouse.warehouseName.includes(state.searchParams.warehouseName))
        .filter(warehouse => state.searchParams.warehouseType === undefined ||
          warehouse.warehouseType === state.searchParams.warehouseType)
        .filter(warehouse => state.searchParams.isActive === undefined ||
          warehouse.isActive === state.searchParams.isActive)
    },
    warehouseTypeOptions: () => {
      return Object.entries(WAREHOUSE_TYPES).map(([value, label]) => ({
        value: parseInt(value),
        label
      }))
    }
  },

  actions: {
    // 获取仓库列表
    async fetchWarehouses() {
      this.loading = true
      this.error = null
      try {
        // 在实际项目中，这里应该调用API
        // const response = await request.get('/api/base/warehouse', {
        //   params: {
        //     page: this.currentPage,
        //     pageSize: this.pageSize,
        //     ...this.searchParams
        //   }
        // })
        // this.warehouses = response.data.items
        // this.total = response.data.total

        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        this.warehouses = mockWarehouses
        this.total = mockWarehouses.length
      } catch (err) {
        this.error = '获取仓库列表失败'
        console.error('Failed to fetch warehouses:', err)
      } finally {
        this.loading = false
      }
    },

    // 获取单个仓库详情
    async fetchWarehouseById(warehouseId: number) {
      this.loading = true
      this.error = null
      try {
        // 模拟API调用
        // const response = await request.get(`/api/base/warehouse/${warehouseId}`)
        // return response.data

        await new Promise(resolve => setTimeout(resolve, 300))
        const warehouse = mockWarehouses.find(item => item.warehouseId === warehouseId)
        if (!warehouse) {
          throw new Error('仓库不存在')
        }
        return warehouse
      } catch (err) {
        this.error = '获取仓库详情失败'
        console.error('Failed to fetch warehouse by id:', err)
        throw err
      } finally {
        this.loading = false
      }
    },

    // 创建仓库
    async createWarehouse(warehouseData: Omit<baseWarehouse, 'warehouseId' | 'createdAt' | 'updatedAt' | 'isDeleted'>) {
      this.loading = true
      this.error = null
      try {
        // 模拟API调用
        // const response = await request.post('/api/base/warehouse', warehouseData)
        // this.warehouses.unshift(response.data)
        // this.total++

        await new Promise(resolve => setTimeout(resolve, 500))
        const newWarehouse: baseWarehouse = {
          ...warehouseData,
          warehouseId: Date.now(), // 模拟生成ID
          createdAt: new Date(),
          updatedAt: new Date(),
          isDeleted: 0
        }
        this.warehouses.unshift(newWarehouse)
        this.total++
        return newWarehouse
      } catch (err) {
        this.error = '创建仓库失败'
        console.error('Failed to create warehouse:', err)
        throw err
      } finally {
        this.loading = false
      }
    },

    // 更新仓库
    async updateWarehouse(warehouseId: number, warehouseData: Partial<baseWarehouse>) {
      this.loading = true
      this.error = null
      try {
        // 模拟API调用
        // const response = await request.put(`/api/base/warehouse/${warehouseId}`, warehouseData)
        // const index = this.warehouses.findIndex(item => item.warehouseId === warehouseId)
        // if (index !== -1) {
        //   this.warehouses[index] = response.data
        // }

        await new Promise(resolve => setTimeout(resolve, 500))
        const index = this.warehouses.findIndex(item => item.warehouseId === warehouseId)
        if (index !== -1) {
          this.warehouses[index] = {
            ...this.warehouses[index],
            ...warehouseData,
            updatedAt: new Date()
          }
          return this.warehouses[index]
        }
        throw new Error('仓库不存在')
      } catch (err) {
        this.error = '更新仓库失败'
        console.error('Failed to update warehouse:', err)
        throw err
      } finally {
        this.loading = false
      }
    },

    // 删除仓库（软删除）
    async deleteWarehouse(warehouseId: number) {
      this.loading = true
      this.error = null
      try {
        // 模拟API调用
        // await request.delete(`/api/base/warehouse/${warehouseId}`)
        // const index = this.warehouses.findIndex(item => item.warehouseId === warehouseId)
        // if (index !== -1) {
        //   this.warehouses.splice(index, 1)
        //   this.total--
        // }

        await new Promise(resolve => setTimeout(resolve, 300))
        const index = this.warehouses.findIndex(item => item.warehouseId === warehouseId)
        if (index !== -1) {
          this.warehouses[index].isDeleted = 1
          // 从当前列表中移除
          this.warehouses.splice(index, 1)
          this.total--
        }
      } catch (err) {
        this.error = '删除仓库失败'
        console.error('Failed to delete warehouse:', err)
        throw err
      } finally {
        this.loading = false
      }
    },

    // 激活/禁用仓库
    async toggleWarehouseStatus(warehouseId: number, isActive: number) {
      this.loading = true
      this.error = null
      try {
        // 模拟API调用
        // await request.patch(`/api/base/warehouse/${warehouseId}/status`, { isActive })
        // const warehouse = this.warehouses.find(item => item.warehouseId === warehouseId)
        // if (warehouse) {
        //   warehouse.isActive = isActive
        //   warehouse.updatedAt = new Date()
        // }

        await new Promise(resolve => setTimeout(resolve, 300))
        const warehouse = this.warehouses.find(item => item.warehouseId === warehouseId)
        if (warehouse) {
          warehouse.isActive = isActive
          warehouse.updatedAt = new Date()
        } else {
          throw new Error('仓库不存在')
        }
      } catch (err) {
        this.error = isActive === 1 ? '激活仓库失败' : '禁用仓库失败'
        console.error(`Failed to ${isActive === 1 ? 'activate' : 'deactivate'} warehouse:`, err)
        throw err
      } finally {
        this.loading = false
      }
    },

    // 设置搜索参数
    setSearchParams(params: Partial<typeof this.searchParams>) {
      this.searchParams = { ...this.searchParams, ...params }
      this.currentPage = 1 // 重置为第一页
    },

    // 清空搜索参数
    resetSearchParams() {
      this.searchParams = {
        warehouseCode: '',
        warehouseName: '',
        warehouseType: undefined,
        isActive: undefined
      }
      this.currentPage = 1
    },

    // 设置分页
    setPagination(page: number, pageSize: number) {
      this.currentPage = page
      this.pageSize = pageSize
    }
  }
})
